package com.xyh.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author:kyle
 * @Date:2020/12/17 - 13:39
 * @Project:spring_demo1
 * @Package:com.xyh.controller
 * @Version:1.0
 */
@Controller
public class IOController {

    //文件下载
    @RequestMapping("/download")
    public String download(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 打印一下文件名
        System.out.println("filename = " + filename);

        // 修改响应流的头信息，改为附件attachment
        response.setHeader("Content-Disposition","attachment;filename:" + filename);

        //获取本地静态文件路径
        String imagesPath = request.getServletContext().getRealPath("images");
        //获取后台文件信息对象 路径 文件名
        File imageFile = new File(imagesPath,filename);
        //将获取的文件对象转换为byte类型的数组
        byte[] bytes = FileUtils.readFileToByteArray(imageFile);

        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //通过输出流向浏览器输出
        outputStream.write(bytes);
        //清空输出流
        outputStream.flush();
        //关闭并释放输出流资源
        outputStream.close();
        //请求重定向
        return "redirect:/index.jsp";
    }

    //文件上传
    @RequestMapping("upload")
    public String upload(@RequestParam("file") MultipartFile file, String imageName, HttpServletRequest request) throws IOException {
        //获取上传文件路径
        String filePath = request.getServletContext().getRealPath("file");
        System.out.println("上传文件路径filePath = " + filePath);
        //获取上传文件名
        String originalFilename = file.getOriginalFilename();
        System.out.println("上传文件名originalFilename = " + originalFilename);
        //保证上传图片名唯一性，不被覆盖
        //截取文件名后缀 .jpg格式
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println("截取文件名后缀suffix = " + suffix);
        //随机值
        String uuid = UUID.randomUUID().toString();
        //新文件全路径名字
        String newFilePath = filePath + "/" + uuid + suffix;
        System.out.println("新文件全路径名字newFilePath = " + newFilePath);
        //上传文件到新的路径
        FileUtils.copyInputStreamToFile(file.getInputStream(),new File(newFilePath) );

        return "redirect:/index.jsp";
    }
}
